package com.manlitech.cloudboot.basebootconfig.redis.scenes.delayjob;

import com.manlitech.cloudboot.basebootconfig.redis.scenes.delayjob.service.DelayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
public class RedisTaskUtil {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    DelayService delayService;

    private static final int CORE_SIZE = Runtime.getRuntime().availableProcessors();
    private static ThreadPoolExecutor taskExecPool = new ThreadPoolExecutor(CORE_SIZE, CORE_SIZE, 0, TimeUnit.SECONDS,
            new LinkedBlockingDeque<>());
    public void asyncZSetTask(String queueName) {
        taskExecPool.execute(() -> {
            for (; ; ) {
                Long nowTimeInMs = System.currentTimeMillis();
                //System.out.println("nowTimeInMs:" + nowTimeInMs);
                Set<String> messages = redisTemplate.opsForZSet().rangeByScore(queueName, 0, nowTimeInMs);
                if (messages != null && messages.size() != 0) {
                    redisTemplate.opsForZSet().removeRangeByScore(queueName, 0, nowTimeInMs);
                    for (String message : messages) {
                        delayService.mainDelaySwitch(queueName,message);
                        logger.info("asyncZSetTask:" + message + " " + nowTimeInMs);
                    }
                    logger.info(redisTemplate.opsForZSet().zCard(queueName).toString());
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
